using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Enemy : MonoBehaviour
{
    [Header("受击")]
    public float BackSpeed;//被击退的速度
    private Vector2 direction;//被击退的方向
    private bool isHit;//是否被攻击
    public float hp;
    public float maxHp=500;
    public bool isDead=false;
    [Header("组件")]
    private Animator enemyAnim;
    private Animator enemyHitAnim;
    private Rigidbody2D enemyRg2D;
    private AnimatorStateInfo info;

    public StatsBar playerHpShow;
    void Start()
    {
        hp = maxHp;
        playerHpShow.Initialize(hp, maxHp);
        enemyAnim = this.GetComponent<Animator>();
        enemyHitAnim = transform.GetChild(0).GetComponent<Animator>();
        enemyRg2D = this.GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        info = enemyAnim.GetCurrentAnimatorStateInfo(0);
        if (isHit)
        {
            enemyRg2D.velocity = direction * BackSpeed;
            if (info.normalizedTime >= 0.6f)
                isHit = false;
        }
    }
    /// <summary>
    /// 受击方向
    /// </summary>
    /// <param name="vector2"></param>
    public void GetHit(Vector2 vector2,float Attack)
    {
        hp -= Attack;
        if (hp <= 0)
        {
            isDead = true;
            Destroy(gameObject);
        }
        else
        {
            playerHpShow.UpdateStart(hp, maxHp);
            enemyAnim.speed = 0.5f;
            transform.localScale = new Vector3(-vector2.x, 1, 1);//更改受击方向
            isHit = true;//被攻击
            enemyAnim.SetTrigger("Hit");//开始播放动画
            enemyHitAnim.SetTrigger("HitAnim");//开始播放动画
            this.direction = vector2;
            enemyAnim.speed = 1f;
        }
    }
}
